<template>
  <div class="app-container">
    <el-form label-width="120px" style="width: 50%">
      <el-form-item label="相册名称">
        <el-input v-model="AlbumInfo.name" />
      </el-form-item>

      <el-form-item label="相册描述">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="AlbumInfo.description"
          maxlength="100"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="照片上传">
        <el-upload
          :on-success="onUploadSuccess"
          :before-upload="beforeUpload"
          :on-preview="onUploadPreview"
          :on-remove="onUploadRemove"
          multiple
          :action="`${UPLOAD_FILE_URL}/admin/show/fileUpload`"
          class="upload-demo"
          list-type="picture-card"
          :file-list="fileList"
          accept=".png, .jpg, .jpeg"
        >
          <i class="el-icon-upload" />
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png/gif文件，且不超过20MB
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>

    <!--图片预览-->
    <el-dialog :visible.sync="dialogImageVisible">
      <img :src="dialogImageUrl" width="100%" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import AlbumApi from '@/api/photo/album'
import { UPLOAD_FILE_URL } from '@/api/path-to-config/config'

const defaultForm = {
  id: '',
  name: '', // 相册名称
  description: '', // 相册描述
  imgUrl: '', // 展示图片
  imgLimit: '', // 选片限制数量
  allImgList: [],
  modifyImgList: []
}

export default {
  data() {
    return {
      AlbumInfo: defaultForm,

      // 接口API地址
      UPLOAD_FILE_URL: UPLOAD_FILE_URL,
      saveBtnDisabled: false,
      fileList: [],

      // 图片预览区域url
      dialogImageUrl: '',
      // 图片预览对话框
      dialogImageVisible: false
    }
  },

  // 监听器
  watch: {
    $route(to, from) {
      console.log('路由变化......')
      console.log(to)
      console.log(from)
      this.init()
    }
  },

  // 生命周期方法（在路由切换，组件不变的情况下不会被调用）
  created() {
    console.log(UPLOAD_FILE_URL)
    this.init()
  },

  methods: {
    // 表单初始化
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 对象拓展运算符：拷贝对象，而不是赋值对象的引用
        this.AlbumInfo = { ...defaultForm }
      }
    },

    saveOrUpdate() {
      // this.saveBtnDisabled = true // 防止表单重复提交
      if (!this.AlbumInfo.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },

    // 新增
    saveData() {
      if (this.AlbumInfo.allImgList.length > 0) {
        this.AlbumInfo.imgUrl = this.AlbumInfo.allImgList[0].imgUrl
      }
      AlbumApi.save(this.AlbumInfo).then((response) => {
        console.log(response)
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/album/list' })
          this.saveBtnDisabled = false
        }
      })
    },

    // 根据id更新记录
    updateData() {
      if (this.AlbumInfo.allImgList.length > 0) {
        this.AlbumInfo.imgUrl = this.AlbumInfo.allImgList[0].imgUrl
      }
      AlbumApi.updateById(this.AlbumInfo).then((response) => {
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/album/list' })
        }
      })
    },

    back() {
      this.$router.push({ path: '/album/list' })
    },

    // 根据id查询记录
    fetchDataById(id) {
      AlbumApi.getById(id).then((response) => {
        this.AlbumInfo = response.data
        // 图片回显
        this.AlbumInfo.allImgList.forEach((item) => {
          let obj = new Object()
          obj.url = item.imgUrl
          this.fileList.push(obj)
        })
      })
    },

    // 文件上传限制条件
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
        return false
      }
      return true
    },

    // 上传图片成功的回调
    onUploadSuccess(res, file) {
      // 填充上传文件列表
      this.AlbumInfo.allImgList.push({
        imgName: file.name,
        imgUrl: file.response.data
      })
    },

    // 上传的文件预览
    onUploadPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    // 删除上传的文件
    onUploadRemove(file, fileList) {
      var list = []
      this.AlbumInfo.allImgList.forEach((item) => {
        if (file.url != item.imgUrl) {
          list.push(item)
        }
      })
      this.AlbumInfo.allImgList = list
    }
  }
}
</script>
<style scoped></style>
